package com.cloud.mkz.core.mybatis;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.cloud.mkz.core.mybatis.constants.MybatisConstants;
import com.cloud.mkz.core.mybatis.resolver.LogicSqlInjector;
import com.cloud.mkz.core.mybatis.resolver.MybatisResultInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * @author SpringCloud
 * @date 2020-03-14
 * mybatis plus 统一配置
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class MybatisAutoConfiguration {
	private final MybatisResultInterceptor mybatisResultInterceptor;

	@Value("${spring.datasource.driver-class-name}")
	private String driver_class_name;

	/**
	 * 分页插件, 对于单一数据库类型来说,都建议配置该值,避免每次分页都去抓取数据库类型
	 */
	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
		if(StrUtil.isEmpty(driver_class_name)){
			mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		}else{
			if(driver_class_name.equals(MybatisConstants.DB2_DRIVER_CLASS_NAME)){
				mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DB2));
			}else{
				mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
			}
		}
		return mybatisPlusInterceptor;
	}

	@Bean
	public String myInterceptor() {
		this.mybatisResultInterceptor.setProperties(new Properties());
		return "mybatisResultInterceptor";
	}

	/**
	 * 逻辑删除插件
	 *
	 * @return LogicSqlInjector
	 */
	@Bean
	public ISqlInjector sqlInjector() {
		return new LogicSqlInjector();
	}
}
